package com.aiti.lulian.service.newCard;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.lulian.constant.MiniProgramVersionConstant;
import com.aiti.lulian.constant.NewCardBusinessConstant;
import com.aiti.lulian.dto.newCard.*;
import com.aiti.lulian.entity.CardEnterpriseTemplate;
import com.aiti.lulian.entity.CardTemplateStyleField;
import com.aiti.lulian.entity.CardUserCardForwardCoverOption;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.newCard.*;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.mapper.newCard.*;
import com.aiti.lulian.service.CardTemplateStyleFieldService;
import com.aiti.lulian.service.CardUserCardForwardCoverOptionService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: 用于迁移旧数据
 * auth fcb
 * date 2025-10-10 18:46
 **/
@Service
@Slf4j
public class TestService {

    @Autowired
    private CardPersonalBaseInfoService cardPersonalBaseInfoService;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;
    @Autowired
    private CardDescriptionService cardDescriptionService;
    @Autowired
    private CardDescriptionMapper cardDescriptionMapper;
    @Autowired
    private CardLinkInfoService cardLinkInfoService;
    @Autowired
    private CardLinkInfoMapper cardLinkInfoMapper;
    @Autowired
    private CardMoreInfoService cardMoreInfoService;
    @Autowired
    private CardMoreInfoMapper cardMoreInfoMapper;
    @Autowired
    private CardPersonalFileInfoService cardPersonalFileInfoService;
    @Autowired
    private CardPersonalFileInfoMapper cardPersonalFileInfoMapper;
    @Autowired
    private CardVideoInfoService cardVideoInfoService;
    @Autowired
    private CardVideoInfoMapper cardVideoInfoMapper;
    @Autowired
    private CardUserCardSettingMapper cardUserCardSettingMapper;
    @Autowired
    private CardVersionService cardVersionService;
    @Autowired
    private NewCardVersionMapper newCardVersionMapper;
    @Autowired
    private CardOperationLogMapper cardOperationLogMapper;
    @Autowired
    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;
    @Autowired
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;
    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;
    @Autowired
    private GxmhSysMapper gxmhSysMapper;
    @Autowired
    private ShowEnterpriseTrialMapper showEnterpriseTrialMapper;
    @Autowired
    private CardEnterpriseTemplateNewMapper cardEnterpriseTemplateNewMapper;
    @Autowired
    private CardEnterpriseComponentMapper cardEnterpriseComponentMapper;
    @Autowired
    private CardEnterpriseComponentService cardEnterpriseComponentService;
    @Autowired
    private CardComponentDataMapper cardComponentDataMapper;
    @Autowired
    private CardComponentDataService cardComponentDataService;
    @Autowired
    private CardEnterpriseTemplateMapper cardEnterpriseTemplateMapper;
    @Autowired
    private CardStyleFieldDataService cardStyleFieldDataService;
    @Autowired
    private CardTemplateStyleFieldService cardTemplateStyleFieldService;
    @Autowired
    private CardTemplateStyleFieldMapper cardTemplateStyleFieldMapper;
    @Autowired
    private CardAuditService cardAuditService;
    @Autowired
    private CardShareConfigService cardShareConfigService;
    @Autowired
    private CardUserCardForwardCoverOptionService cardUserCardForwardCoverOptionService;
    @Autowired
    private TestMapper testMapper;
    @Autowired
    private CardPrivacySettingMapper cardPrivacySettingMapper;
    @Autowired
    private CardDefaultTemplateMapper cardDefaultTemplateMapper;

    @Transactional(rollbackFor = Exception.class)
    public void createEnterpriseAdminCard(String enterpriseId, String enterpriseAdminUsername, Integer zhengFu) {
        if(StrUtil.isBlank(enterpriseId)) {
            throw new BusinessException("企业标识不能为空");
        }
        LuLianEnterprise luLianEnterprise = luLianEnterpriseMapper.selectById(enterpriseId);
        // 1. 查询企业管理员角色baseId
        List<SysUserRoleDto>  sysUserRoleBaseIdList;
        if(zhengFu == 0) {
            sysUserRoleBaseIdList = testMapper.querySysUserRoleBaseId(enterpriseId, "043ea2e3e02c4aa591df1f83e65069bc");
        }else if(zhengFu == 1){
            sysUserRoleBaseIdList = testMapper.querySysUserRoleBaseId(enterpriseId, "cc06b294d519480c8a9a62670c416e17");
        }else {
            throw new BusinessException("请指定正确的政府类型");
        }
        if(CollectionUtil.isEmpty(sysUserRoleBaseIdList) || sysUserRoleBaseIdList.size() > 1) {
            if(StrUtil.isBlank(enterpriseAdminUsername)) {
                throw new BusinessException("未查询到当前企业的企业管理员或查询到多个企业管理员。请指定管理员账号");
            }else {
                // 删除其他的管理员，只留下指定的管理员
                String adminUserId = gxmhSysMapper.queryUserIdByUsername(enterpriseAdminUsername);
                sysUserRoleBaseIdList.removeIf(sysUserRoleDto -> !sysUserRoleDto.getUserId().equals(adminUserId));
            }
        }
        if(CollectionUtil.isEmpty(sysUserRoleBaseIdList) || sysUserRoleBaseIdList.size() != 1) {
            throw new BusinessException("未找到企业唯一的企业管理员");
        }
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(sysUserRoleBaseIdList.get(0).getUserId());
        // 2. 设置用户角色表的企业id
        testMapper.updateSysUserRoleEnterpriseId(enterpriseId, sysUserRoleBaseIdList.get(0).getBaseId());
        // 3. 查询默认模板
        String defaultTemplateId = cardEnterpriseTemplateNewMapper.queryDefaultTemplateId();
        // 4. 创建企业自己的两个模板表数据
        String templateId = this.createTemplateNew(enterpriseId, sysUserDto.getBaseId(), defaultTemplateId);
        List<CardEnterpriseComponent> templateComponentData = this.createTemplateComponentData(templateId, defaultTemplateId, enterpriseId, luLianEnterprise);
        // 创建模板的分享配置
        CardShareConfig cardShareConfig = cardShareConfigService.buildCardShareConfig(enterpriseId, templateId);
        cardShareConfigService.save(cardShareConfig);
        // 5. 创建用户自己的名片
        CardBaseInfo cardBaseInfo = this.buildEnterpriseCardInfo(luLianEnterprise, sysUserDto);
        cardBaseInfo.setTemplateId(templateId);
        cardPersonalBaseInfoService.save(cardBaseInfo);
        // 4.3 给当前企业生成旧的模板表数据 （生成card_enterprise_template数据）
        CardEnterpriseTemplate oldTemplateTableData = this.createTemplate(enterpriseId, sysUserDto.getBaseId(), templateId, defaultTemplateId);
        cardEnterpriseTemplateMapper.insert(oldTemplateTableData);
        // 4.4 根据预设模板创建卡片字段数据
        List<CardTemplateStyleField> templateStyleFieldList = this.createTemplateStyleField(oldTemplateTableData.getBaseId(), sysUserDto.getBaseId(), defaultTemplateId, sysUserDto, luLianEnterprise.getBaseName(), luLianEnterprise.getAddress());
        // 5. 根据上面的模板，生成名片的具体数据，包括卡片字段和组件
        // 5.1 生成名片的卡片数据。根据表单里面填写的数据和默认模板上的字段属性按名字匹配，只保存能匹配上的
        this.createStyleFieldData(sysUserDto, cardBaseInfo.getBaseId(), templateStyleFieldList,luLianEnterprise.getBaseName(), luLianEnterprise.getAddress());
        // 5.2 生成名片的组件数据
        this.createCardComponentData(templateComponentData, cardBaseInfo.getBaseId());
        // 生成名片的转发封面
        this.createDefaultForwardCover(sysUserDto.getBaseId(), cardBaseInfo.getBaseId(), cardShareConfig.getCoverUrl(), cardShareConfig.getType(), cardShareConfig.getCoverUrlBaseId());
        // 6. 将当前生成的名片设置为自动审核通过
        this.auditPass(luLianEnterprise.getBaseId(), templateId, cardBaseInfo.getBaseId(), sysUserDto.getBaseId());
        // 4.2.1 初始化名片隐私设置
        cardPrivacySettingMapper.insert(CardPrivacySetting.builder().baseId(IdUtil.simpleUUID()).userId(cardBaseInfo.getUserId()).cardId(cardBaseInfo.getBaseId()).baseUpdateTime(new Date()).build());
    }

    @Transactional(rollbackFor = Exception.class)
    public void createEnterpriseUserCard(String enterpriseId) {
        if(StrUtil.isBlank(enterpriseId)) {
            throw new BusinessException("企业标识不能为空");
        }
        LuLianEnterprise luLianEnterprise = luLianEnterpriseMapper.selectById(enterpriseId);
        // 查询这个企业下的所有用户，剔除已经有名片数据的用户，比如企业管理员
        List<String> enterpriseUserIdList = testMapper.queryEnterpriseUserIdList(enterpriseId);
        List<String> createUserCardUserIdList = new ArrayList<>();
        if(CollectionUtil.isEmpty(enterpriseUserIdList)) {
            return;
        }
        // 查询该企业已经有名片的用户id
        List<String> enterpriseCardUserIdList = testMapper.queryEnterpriseCardUserIdList(enterpriseId);
        // 剔除已经有名片数据的用户
        for(String userId : enterpriseUserIdList) {
            if(!enterpriseCardUserIdList.contains(userId)) {
                createUserCardUserIdList.add(userId);
            }
        }
        // 查询这个企业下所有的模板
        List<String> enterpriseNewTemplateIdList = testMapper.queryEnterpriseNewTemplateIdList(enterpriseId);
        if(CollectionUtil.isEmpty(enterpriseNewTemplateIdList)) {
            throw new BusinessException("该企业没有模板，无法创建名片数据");
        }
        // 在每个模板下，都创建所有用户的名片相关数据
        for(String newTemplateId : enterpriseNewTemplateIdList) {
            String oldTemplateId = testMapper.queryOldTemplateId(newTemplateId);
            // 这个属性列表有可能是空的
            List<CardTemplateStyleFieldBo> cardTemplateStyleFieldBos = cardTemplateStyleFieldMapper.queryListByOldTemplateId(oldTemplateId);
            for(String userId : createUserCardUserIdList) {
                SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(userId);
                if(sysUserDto == null) {
                    log.warn("用户不存在，无法创建名片数据，userId：{}", userId);
                    continue;
                }
                 // 名片数据
                CardBaseInfo cardBaseInfo = this.buildEnterpriseCardInfo(luLianEnterprise, sysUserDto);
                cardBaseInfo.setTemplateId(newTemplateId);
                cardPersonalBaseInfoService.save(cardBaseInfo);
                // 创建用户隐私设置
                cardPrivacySettingMapper.insert(CardPrivacySetting.builder().baseId(IdUtil.simpleUUID()).userId(cardBaseInfo.getUserId()).cardId(cardBaseInfo.getBaseId()).baseUpdateTime(new Date()).build());
                // 名片的卡片字段数据
                this.createStyleFieldData2(sysUserDto, cardBaseInfo.getBaseId(), cardTemplateStyleFieldBos, luLianEnterprise.getBaseName());
                // 名片的组件数据
                List<CardEnterpriseComponent> templateComponentList = cardEnterpriseComponentMapper.queryCardEnterpriseComponentList(newTemplateId);
                cardComponentDataService.createCardComponentData(templateComponentList, cardBaseInfo.getBaseId());
                // 创建转发封面信息
                CardShareConfig cardShareConfig = cardShareConfigService.queryCardShareConfig(enterpriseId, newTemplateId);
                this.createDefaultForwardCover(sysUserDto.getBaseId(), cardBaseInfo.getBaseId(), cardShareConfig.getCoverUrl(), cardShareConfig.getType(), cardShareConfig.getCoverUrlBaseId());
                // 5. 将用户添加到企业之下，已经在企业之下了
                // this.bindEnterprise(dto.getEnterpriseId(), dto.getUserId());
                // 设置个人角色。已经有角色了
                // this.insertUserRole(dto.getEnterpriseId(), dto.getUserId());
                // 6. 将当前生成的名片设置为自动审核通过
                this.auditPass(luLianEnterprise.getBaseId(), newTemplateId, cardBaseInfo.getBaseId(), sysUserDto.getBaseId());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void addCardAddress(List<String> enterpriseIdList) {
        if(CollectionUtil.isEmpty(enterpriseIdList)) {
            return;
        }
        for(String enterpriseId : enterpriseIdList) {
            LuLianEnterprise luLianEnterprise = luLianEnterpriseMapper.selectById(enterpriseId);
            // 当前企业下所有的模板
            List<String> enterpriseNewTemplateIdList = testMapper.queryEnterpriseNewTemplateIdList(enterpriseId);
            for(String newTemplateId : enterpriseNewTemplateIdList) {
                List<CardStyleFieldData> cardStyleFieldDataList = new ArrayList<>();
                String oldTemplateId = testMapper.queryOldTemplateId(newTemplateId);
                // 查询地址字段
                CardTemplateStyleFieldBo cardTemplateStyleFieldBo = testMapper.queryCardTemplateStyleFieldBo(oldTemplateId);
                if(cardTemplateStyleFieldBo == null) {
                    continue;
                }
                // 该企业当前模板下所有名片id
                List<String> cardIdList = testMapper.queryCardIdList(enterpriseId, newTemplateId);
                if(CollectionUtil.isNotEmpty(cardIdList)) {
                    for(String cardId : cardIdList) {
                        // 查询这张名片是否已经有地址字段
                        Integer addressStyleCount = testMapper.queryCardStyleValue(cardId, cardTemplateStyleFieldBo.getBaseId());
                        if(addressStyleCount > 0) {
                            continue;
                        }
                        CardStyleFieldData fieldData = new CardStyleFieldData();
                        fieldData.setBaseId(IdUtil.simpleUUID());
                        fieldData.setCardId(cardId);
                        fieldData.setStyleFieldId(cardTemplateStyleFieldBo.getBaseId());
                        JSONObject map = JSONObject.parseObject(cardTemplateStyleFieldBo.getExtraInfo(), JSONObject.class);
                        fieldData.setStyleFieldValue(map.getString("text"));
                        cardStyleFieldDataList.add(fieldData);
                    }
                }
                if(CollectionUtil.isNotEmpty(cardStyleFieldDataList)) {
                    cardStyleFieldDataService.saveBatch(cardStyleFieldDataList);
                }
            }
        }
    }

    private void auditPass(String enterpriseId, String templateId, String cardId, String userId) {
        CardAudit cardAudit = new CardAudit();
        cardAudit.setBaseId(IdUtil.simpleUUID());
        cardAudit.setEnterpriseId(enterpriseId);
        cardAudit.setTemplateId(templateId);
        cardAudit.setCardId(cardId);
        cardAudit.setCardStatus(NewCardBusinessConstant.CARD_STATUS_3);
        cardAudit.setBaseCreateBy(userId);
        cardAudit.setBaseUpdateBy(userId);
        cardAudit.setBaseCreateTime(new Date());
        cardAudit.setBaseUpdateTime(new Date());
        cardAudit.setActiveTime(new Date());
        cardAudit.setUserId(userId);
        cardAuditService.save(cardAudit);
    }

    public void createCardComponentData(List<CardEnterpriseComponent> templateComponentData, String cardId) {
        if(CollectionUtil.isEmpty(templateComponentData)) {
            return;
        }
        List<CardComponentData> componentDataList = new ArrayList<>();
        for(CardEnterpriseComponent templateComponent : templateComponentData) {
            CardComponentData componentData = new CardComponentData();
            componentData.setBaseId(IdUtil.simpleUUID());
            componentData.setCardId(cardId);
            componentData.setTemplateComponentId(templateComponent.getBaseId());
            componentData.setComponentMetaData(templateComponent.getComponentMetaData());
            componentData.setSort(templateComponent.getSort());

            componentDataList.add(componentData);
        }
        cardComponentDataService.saveBatch(componentDataList);
    }

    public void createDefaultForwardCover(String userId, String cardId, String coverUrl, String coverUrlType, String coverUrlBaseId) {
        CardUserCardForwardCoverOption coverOption = new CardUserCardForwardCoverOption();
        coverOption.setBaseId(IdUtil.simpleUUID());
        // 先查原来的转发封面，查不到再使用模板上的
        String url = testMapper.queryUserCoverUrl(userId);
        if(StrUtil.isEmpty(url)) {
            coverOption.setUrl(coverUrl);
            // 老数据属于自定义这里都是null
            coverOption.setCoverUrlBaseId(coverUrlBaseId);
        }else {
            coverOption.setUrl(url);
            coverOption.setCoverUrlBaseId(null);
        }
        coverOption.setUserId(userId);
        coverOption.setCardId(cardId);
        coverOption.setCustomFlag("1");
        coverOption.setVersion("2");
        coverOption.setTemplateType("0");
        coverOption.setCreator(userId);
        coverOption.setUpdateBy(userId);
        coverOption.setHelloWordType(0);
        coverOption.setHelloWord(cardDefaultTemplateMapper.queryDefaultHelloWord());
        coverOption.setType(coverUrlType);

        cardUserCardForwardCoverOptionService.save(coverOption);
    }

    private void createStyleFieldData(SysUserDto dto, String cardId, List<CardTemplateStyleField> cardTemplateStyleFields, String enterpriseName, String enterpriseAddress) {
        // 按名称匹配字段
        List<CardStyleFieldData> cardStyleFieldDataList = new ArrayList<>();
        for(CardTemplateStyleField cardTemplateStyleField: cardTemplateStyleFields) {
            if(cardTemplateStyleField.getBaseName().equals("姓名")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getRealname());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("公司")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(enterpriseName);
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("职位")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getPosition());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("手机")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getMobile());
                cardStyleFieldDataList.add(fieldData);
            } else if(cardTemplateStyleField.getBaseName().equals("邮箱")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getEmail());
                cardStyleFieldDataList.add(fieldData);
            } else if(cardTemplateStyleField.getBaseName().equals("地址")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(enterpriseAddress);
                cardStyleFieldDataList.add(fieldData);
            }
        }
        if(CollectionUtil.isNotEmpty(cardStyleFieldDataList)) {
            cardStyleFieldDataService.saveBatch(cardStyleFieldDataList);
        }
    }

    private void createStyleFieldData2(SysUserDto dto, String cardId, List<CardTemplateStyleFieldBo> cardTemplateStyleFields, String enterpriseName) {
        if(CollectionUtil.isEmpty(cardTemplateStyleFields)) {
            log.warn("模板的字段属性为空不创建名片的字段数据，{}", enterpriseName);
            return;
        }
        // 按名称匹配字段
        List<CardStyleFieldData> cardStyleFieldDataList = new ArrayList<>();
        for(CardTemplateStyleFieldBo cardTemplateStyleField: cardTemplateStyleFields) {
            if(cardTemplateStyleField.getBaseName().equals("姓名")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getRealname());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("公司")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(enterpriseName);
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("职位")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getPosition());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("手机")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getMobile());
                cardStyleFieldDataList.add(fieldData);
            } else if(cardTemplateStyleField.getBaseName().equals("邮箱")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getEmail());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("地址")) {
                JSONObject map = JSONObject.parseObject(cardTemplateStyleField.getExtraInfo(), JSONObject.class);
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                // 地址取模板上的地址
                String address = map.getString("text");
                fieldData.setStyleFieldValue(address);
                cardStyleFieldDataList.add(fieldData);
            }
        }
        if(CollectionUtil.isNotEmpty(cardStyleFieldDataList)) {
            cardStyleFieldDataService.saveBatch(cardStyleFieldDataList);
        }
    }

    private List<CardTemplateStyleField> createTemplateStyleField(String oldTemplateId, String userId, String defaultTemplateId, SysUserDto sysUserDto, String enterpriseName, String enterpriseAddress) {
        // 预设模板的字段属性
        CardEnterpriseTemplate defaultTemplateInfo = cardEnterpriseTemplateMapper.queryTemplateInfo(defaultTemplateId);
        List<CardTemplateStyleFieldBo> cardTemplateStyleFields = cardTemplateStyleFieldMapper.queryListByOldTemplateId(defaultTemplateInfo.getBaseId());
        List<CardTemplateStyleField> list = new ArrayList<>();
        for(CardTemplateStyleFieldBo templateStyleField : cardTemplateStyleFields) {
            CardTemplateStyleField newTemplateStyleField = new CardTemplateStyleField();
            BeanUtils.copyProperties(templateStyleField, newTemplateStyleField);

            newTemplateStyleField.setBaseId(IdUtil.simpleUUID());
            newTemplateStyleField.setTemplateId(oldTemplateId);
            newTemplateStyleField.setCreator(userId);
            newTemplateStyleField.setBaseCreateTime(new Date());
            newTemplateStyleField.setUpdateBy(userId);
            newTemplateStyleField.setBaseUpdateTime(new Date());
            JSONObject map = JSONObject.parseObject(templateStyleField.getExtraInfo(), JSONObject.class);
            // 回填表单上的手机、姓名、邮箱、公司等字段到新模板上
            if("姓名".equals(templateStyleField.getBaseName())) {
                map.put("text", sysUserDto.getRealname());
            }else if("公司".equals(templateStyleField.getBaseName())) {
                map.put("text", enterpriseName);
            }else if("手机".equals(templateStyleField.getBaseName())) {
                map.put("text", sysUserDto.getMobile());
            }else if("邮箱".equals(templateStyleField.getBaseName())) {
                map.put("text", sysUserDto.getEmail());
            }else if("职位".equals(templateStyleField.getBaseName())) {
                map.put("text", sysUserDto.getPosition());
            }else if("地址".equals(templateStyleField.getBaseName())) {
                if(StrUtil.isEmpty(enterpriseAddress)) {
                    map.put("text", "");
                }else {
                    map.put("text", enterpriseAddress);
                }
            }
            newTemplateStyleField.setExtraInfo(map);
            list.add(newTemplateStyleField);
        }
        if(!list.isEmpty()) {
            cardTemplateStyleFieldService.saveBatch(list);
        }
        return list;
    }

    private CardEnterpriseTemplate createTemplate(String enterpriseId, String userId, String newTemplateId, String defaultTemplateId) {
        String templateId = IdUtil.simpleUUID();
        CardEnterpriseTemplate defaultTemplateInfo = cardEnterpriseTemplateMapper.queryTemplateInfo(defaultTemplateId);
        if(defaultTemplateInfo == null) {
            throw new BusinessException("未查询到默认的模板信息");
        }
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();
        BeanUtils.copyProperties(defaultTemplateInfo, template);
        template.setBaseId(templateId);
        template.setVersion("2");
        template.setEnterpriseId(enterpriseId);
        template.setUpdateBy(userId);
        template.setBaseUpdateTime(new Date());
        template.setIsDelete("0");
        template.setCreator(userId);
        template.setBaseCreateTime(new Date());
        template.setNewTemplateId(newTemplateId);
        return template;
    }

    private CardBaseInfo buildEnterpriseCardInfo(LuLianEnterprise luLianEnterprise, SysUserDto sysUserDto) {
        Date now = new Date();
        CardBaseInfo cardBaseInfo = new CardBaseInfo();
        String baseId = IdUtil.simpleUUID();
        cardBaseInfo.setBaseId(baseId);
        //cardBaseInfo.setEnterpriseUseType(dto.getEnterpriseUseType());
        cardBaseInfo.setUserId(sysUserDto.getBaseId());
        cardBaseInfo.setName(sysUserDto.getRealname());
        cardBaseInfo.setEnterpriseId(luLianEnterprise.getBaseId());
        cardBaseInfo.setEnterpriseName(luLianEnterprise.getBaseName());
        cardBaseInfo.setPositionOne(sysUserDto.getPosition());
        cardBaseInfo.setEnterpriseMobile(sysUserDto.getMobile());
        cardBaseInfo.setEnterpriseEmail(sysUserDto.getEmail());
        cardBaseInfo.setCardVersion(MiniProgramVersionConstant.getCardVersionByEnterpriseVersion(luLianEnterprise.getMiniProgramVersion()));
        cardBaseInfo.setExpireTime(luLianEnterprise.getExpireTime());
        cardBaseInfo.setUseResourceType(NewCardBusinessConstant.CARD_USE_RESOURCE_TYPE_3);
        cardBaseInfo.setBaseCreateBy(sysUserDto.getBaseId());
        cardBaseInfo.setBaseCreateTime(now);
        cardBaseInfo.setBaseUpdateBy(sysUserDto.getBaseId());
        cardBaseInfo.setBaseUpdateTime(now);
        cardBaseInfo.setIsDelete(0);
        String url = testMapper.queryUserCoverUrl(sysUserDto.getBaseId());
        cardBaseInfo.setPubScreenshotUrl(url);
        // 设置是否当前在用
        Integer currentUse = cardPersonalBaseInfoMapper.queryCurrentUseCardCount(sysUserDto.getBaseId());
        cardBaseInfo.setCurrentUse(currentUse == 0 ? 1 : 0);
        return cardBaseInfo;
    }

    private List<CardEnterpriseComponent> createTemplateComponentData(String templateId, String defaultTemplateId, String enterpriseId, LuLianEnterprise luLianEnterprise) {
        List<CardEnterpriseComponent> templateComponentList = cardEnterpriseComponentMapper.queryCardEnterpriseComponentList(defaultTemplateId);
        if(CollectionUtil.isEmpty(templateComponentList)) {
            return null;
        }
        List<CardEnterpriseComponent> componentDataList = new ArrayList<>();
        for(CardEnterpriseComponent templateComponent : templateComponentList) {
            CardEnterpriseComponent newTemplateComponent = new CardEnterpriseComponent();
            newTemplateComponent.setBaseId(IdUtil.simpleUUID());
            newTemplateComponent.setTemplateId(templateId);
            newTemplateComponent.setComponentType(templateComponent.getComponentType());
            // 如果是荣誉资质组件，将之前的荣誉资质设置上
            if(NewCardBusinessConstant.ENTERPRISE_QUALIFICATION.equals(templateComponent.getComponentType())) {
                List<String> qualificationList = testMapper.queryEnterpriseQualification(enterpriseId);
                if(CollectionUtil.isNotEmpty(qualificationList)) {
                    JSONObject map = JSONObject.parseObject(templateComponent.getComponentMetaData(), JSONObject.class);
                    JSONArray honorList = map.getJSONArray("honorList");
                    for(String pic : qualificationList) {
                        JSONObject honor = new JSONObject();
                        honor.put("imgUrl", pic);
                        honorList.add(honor);
                    }
                    templateComponent.setComponentMetaData(map.toJSONString());
                }

            }
            // VR实景数据
            if(NewCardBusinessConstant.ENTERPRISE_REALITY.equals(templateComponent.getComponentType())) {
                EnterpriseMediaDto enterpriseMediaDto = cardEnterpriseTemplateNewMapper.queryEnterpriseMediaInfo(enterpriseId);
                JSONObject map = JSONObject.parseObject(templateComponent.getComponentMetaData(), JSONObject.class);
                if(StrUtil.isNotBlank(luLianEnterprise.getHyMainPic())) {
                    map.put("hyMainPic", luLianEnterprise.getHyMainPic());
                }
                if(StrUtil.isNotBlank(luLianEnterprise.getVrGif())) {
                    map.put("vrGif", luLianEnterprise.getVrGif());
                }
                if(StrUtil.isNotBlank(luLianEnterprise.getMainProducts())) {
                    map.put("mainProducts", luLianEnterprise.getMainProducts());
                }
                if(enterpriseMediaDto != null) {
                    map.put("mediaPath", enterpriseMediaDto.getMediaPath());
                }
                templateComponent.setComponentMetaData(map.toJSONString());
            }
            newTemplateComponent.setComponentMetaData(templateComponent.getComponentMetaData());
            newTemplateComponent.setComponentBusinessData(templateComponent.getComponentBusinessData());
            newTemplateComponent.setSort(templateComponent.getSort());
            newTemplateComponent.setComponentPermission(templateComponent.getComponentPermission());
            newTemplateComponent.setComponentPageId(IdUtil.simpleUUID());
            componentDataList.add(newTemplateComponent);
        }
        cardEnterpriseComponentService.saveBatch(componentDataList);
        return componentDataList;
    }

    private String createTemplateNew(String enterpriseId, String userId, String defaultTemplateId) {
        String templateId = IdUtil.simpleUUID();
        CardEnterpriseTemplateNew defaultTemplateInfo = cardEnterpriseTemplateNewMapper.selectById(defaultTemplateId);
        if(defaultTemplateInfo == null) {
            throw new BusinessException("未查询到默认的模板信息");
        }
        CardEnterpriseTemplateNew newTemplate = new CardEnterpriseTemplateNew();
        BeanUtils.copyProperties(defaultTemplateInfo, newTemplate);
        newTemplate.setBaseId(templateId);
        newTemplate.setEnterpriseId(enterpriseId);
        newTemplate.setSourceTemplateId(defaultTemplateId);
        newTemplate.setVersion("2");
        newTemplate.setBaseUpdateBy(userId);
        newTemplate.setBaseUpdateTime(new Date());
        newTemplate.setIsDelete(0);
        newTemplate.setBaseCreateBy(userId);
        newTemplate.setBaseCreateTime(new Date());
        cardEnterpriseTemplateNewMapper.insert(newTemplate);
        return templateId;
    }

}
